<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="user-scalable=no,width=device-width,initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>

<ul class="list" id="list"></ul>

<script src="js/iconFile.js"></script>
<script>
    function getList(){
        let audioArr = [];
        for(let i=1;i<8;i++){
            audioArr.push('piano/a'+i+'.mp3');
        }
        for(let i=1;i<9;i++){
            audioArr.push('piano/b'+i+'.mp3');
        }
        return audioArr
    }
    let audioArr = getList();
    let num = 0;
    function loadFile(num){
        let audioEle = new Audio();
        audioEle.src = audioArr[num];
        audioEle.load();
        audioEle.addEventListener('canplaythrough',()=>{
            if(num < audioArr.length-1){
                loadFile(++num);
            }
        });
    }
    loadFile(num);

    createPiano();
    function createPiano(){
        list.innerHTML = [...'.'.repeat(15)].map((item,index)=>{
            if(icon[index]){
                return `<li><div class="icon">${icon[index].data}</div></li>`
            }
            return `<li>${index+1}</li>`
        }).join('');
    }

    let dot = document.querySelectorAll('li');
    Array.from(dot).forEach((item,index)=>{
        item.onclick = function(){
            let audioEle = new Audio();
            audioEle.src = audioArr[index];
            audioEle.load();
            audioEle.addEventListener('canplaythrough',()=>{
                audioEle.play();
            });

            this.classList.remove('active');
            setTimeout(()=>{
                this.classList.add('active');
            },100)
        }
    })

    let objFre = {
        a65:0,
        a83:1,
        a68:2,
        a70:3,
        a71:4,
        a72:5,
        a74:6,
        a75:7,
        a76:8,
        a186:9,
        a222:10,
        a90:11,
        a88:12,
        a67:13,
        a86:14
    }

    let now = {};
    document.onkeydown = function(ev){
        let num = 'a'+ev.keyCode;
        if(''+objFre[num] && !now[num]){
            now[num] = true;
            let audioEle = new Audio();
            audioEle.src = audioArr[objFre[num]];
            audioEle.load();
            audioEle.addEventListener('canplaythrough',()=>{
                audioEle.play();
            });

            dot[objFre[num]].classList.remove('active');
            setTimeout(()=>{
                dot[objFre[num]].classList.add('active');
            })
        }
    }

    document.onkeyup = function(ev){
        let num = 'a'+ev.keyCode
        if(now[num]){
            now[num] = false;
        }
    }
</script>

</body>
</html>